import easyocr
import re
import time
import os
from ruamel.yaml import YAML


# 图片转文字,并按从左到右的顺序排列
def image_to_text(image):
    # 创建OCR对象
    reader = easyocr.Reader(['en'])
    image_text = reader.readtext(image)

    if isinstance(image_text, list):
        n = len(image_text)
        for i in range(n - 1):
            for j in range(0, n - i - 1):
                # 根据坐标位置X的大小排序，大的往后
                if image_text[j][0][0] > image_text[j + 1][0][0]:
                    image_text[j], image_text[j + 1] = image_text[j + 1], image_text[j]

        original = ''
        for (bbox, string, confidence) in image_text:
            original += string

        # 正则过滤掉除字母数字以外的其余字符
        pattern = '[\W_]+'
        result = re.sub(pattern, '', original)
    return result


# 载入配置文件
def load_config():
    config_path = os.path.join(os.path.dirname(__file__), 'config')
    if os.path.exists(config_path):
        config = os.path.join(config_path, 'config.yaml')
        yaml = YAML(typ='safe')
        with open(config, "r", encoding='utf-8') as file:
            data = yaml.load(file)

        return data


def create_dir():
    data = load_config()
    info = data.get('base_info')
    dir_name = info.get('files')
    files = os.path.join(os.path.dirname(__file__), dir_name)
    if not os.path.exists(files):
        os.makedirs(files)
    day = time.strftime("%Y-%m-%d", time.localtime())
    current_dir = os.path.join(files, day)
    if not os.path.exists(current_dir):
        os.makedirs(current_dir)
    return current_dir


# if __name__ == '__main__':
#     data = load_config()
#     devices = data.get('steps')[2]
#     datas = devices.get('alldevice').get('data')
#     for item in datas:
#         for choice, obj in item.items():
#             for status, projects in obj.items():
#                 print("{}: {}".format(status, projects))
#                 for pro in projects:
#                     print(pro)
